package com.dsdl.chatapp.module.login;

import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.dsdl.chatapp.BaseActivity;
import com.dsdl.chatapp.R;
import com.dsdl.chatapp.common.utils.LogUtil;
import com.dsdl.chatapp.common.utils.SPUtil;
import com.dsdl.chatapp.common.utils.StringUtils;
import com.dsdl.chatapp.contacts.Constant;
import com.dsdl.chatapp.module.service.ChatService;
import com.dsdl.chatapp.common.utils.connect.HttpManager;
import com.dsdl.chatapp.common.utils.connect.RequestParam;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class LoginActivity extends BaseActivity implements View.OnClickListener{
    private static String TAG = "LoginActivity";
    private EditText etUserPhone;
    private EditText etCode;
    private TextView tvGetCode;

    private TimeCount timeCount;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        initView();
    }

    private void initView(){
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar_login);
        setSupportActionBar(toolbar);
        tvGetCode = (TextView) findViewById(R.id.tv_code);
        tvGetCode.setOnClickListener(this);
        findViewById(R.id.btn_login).setOnClickListener(this);
        etUserPhone = (EditText) findViewById(R.id.et_login_phone);
        etCode = (EditText) findViewById(R.id.et_login_code);
        timeCount = new TimeCount(60000, 1000);
        initListener(toolbar);
    }
    private void initListener(Toolbar toolbar){
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.tv_code:
                timeCount.start();
                getCode();
                break;
            case R.id.btn_login:
                login();
                break;
            default:
                break;
        }
    }

    /**
     * 获取验证码
     */
    private void getCode(){
        final String userPhone = etUserPhone.getText().toString();
        if (TextUtils.isEmpty(userPhone)){
            Toast.makeText(this,"请输入手机号",Toast.LENGTH_SHORT).show();
            return;
        }
        if (userPhone.length() != 11 || !userPhone.startsWith("1")){
            Toast.makeText(this,"请输入手机号",Toast.LENGTH_SHORT).show();
            return;
        }
        List<RequestParam> params = new ArrayList<>();
        params.add(new RequestParam("phone",userPhone));
        HttpManager.getInstance().get("/getcode", params,new HttpManager.CommonCallBack() {
            @Override
            public void success(String response) {
                LogUtil.d(TAG,response);
                SPUtil.setSharedStringData(Constant.USER_PHONE,userPhone);
            }

            @Override
            public void fails(int status, String errorMessage) {
                LogUtil.d(TAG,errorMessage);
            }
        });

    }

    /**
     * 登录
     */
    private void login(){
        String userPhone = etUserPhone.getText().toString();
        SPUtil.setSharedStringData(Constant.USER_PHONE,userPhone);
        String code = etCode.getText().toString();
        if (TextUtils.isEmpty(userPhone)){
            Toast.makeText(this,"请输入手机号",Toast.LENGTH_SHORT).show();
            return;
        }
        if (userPhone.length() != 11 || !userPhone.startsWith("1")){
            Toast.makeText(this,"请输入正确格式的手机号",Toast.LENGTH_SHORT).show();
            return;
        }
        if (TextUtils.isEmpty(code)){
            Toast.makeText(this,"请输入验证码",Toast.LENGTH_SHORT).show();
            return;
        }
        List<RequestParam> requestParams = new ArrayList<>();
        requestParams.add(new RequestParam("phone",userPhone));
        requestParams.add(new RequestParam("code",code));

        HttpManager.getInstance().get("/login", requestParams, new HttpManager.CommonCallBack() {
            @Override
            public void success(String response) {
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    String uuid = jsonObject.optString("token");
                    SPUtil.setSharedStringData(Constant.USER_TOKEN,uuid);
                    if (!StringUtils.isEmpty(SPUtil.getSharedStringData(Constant.USER_PHONE))
                            && !StringUtils.isEmpty(SPUtil.getSharedStringData(Constant.USER_TOKEN))){
                        startService(new Intent(LoginActivity.this, ChatService.class));
                        finish();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void fails(int status, String errorMessage) {
                LogUtil.d(TAG,errorMessage);
            }
        });
    }

    /**
     * 倒计时
     */
    private class TimeCount extends CountDownTimer {

        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);

        }

        @Override
        public void onTick(long millisUntilFinished) {
            tvGetCode.setClickable(false);
            tvGetCode.setText(millisUntilFinished / 1000 + "s");
        }

        @Override
        public void onFinish() {
            tvGetCode.setText("重新验证");
            tvGetCode.setClickable(true);

        }
    }
}
